package com.xyz.androidiptest;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private String TAG = "MainActivity";

    private IBookManager bookManager;;

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            bookManager = IBookManager.Stub.asInterface(service);
            try {
                //TODO  getBookList是一个耗时的方法，但是客户端调用的时候是在UI线程中，如果多次调用后面会出现ANR
                List<Book> bookList = bookManager.getBookList();
                Log.e("bookList", bookList.toString());

                bookManager.addBook(new Book(3, "中国通史"));
                List<Book> newBookList = bookManager.getBookList();
                Log.e("bookList", newBookList.toString());

                bookManager.registerListenner(bookArrivedListenner);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            bookManager = null;
        }
    };

    private IOnNewBookArrivedListenner bookArrivedListenner = new IOnNewBookArrivedListenner.Stub() {
        @Override
        public void onNewBookArried(Book newBook) throws RemoteException {
            Log.e("TAG", "添加新书了啊，同学们快来领书了:" + newBook.toString());
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent(this, BookManagerService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(bookManager != null && bookManager.asBinder().isBinderAlive()) {
            Log.e(TAG, "onDestory");
            try {
                bookManager.unregisterListenner(bookArrivedListenner);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        unbindService(mConnection);
    }
}
